from flask import Blueprint, request, jsonify,  current_app, make_response
import config, json
import logging, os
from utils import common
from utils.db import client
from copy import deepcopy

user_bp = Blueprint('user', __name__, url_prefix='/user')

# user_bp = common.add_url_to_bp(os.path.dirname(__file__), user_bp)

# import config
# from utils.db import client
@user_bp.route('/register', methods=['POST'])
def register():
    params = request.json
    result = current_app.config['DB'].register_user(params)
    if isinstance(result, str):
        return jsonify({'code':500, 'message':msg})
    else:
        return jsonify({'code':0})

@user_bp.route('/login', methods=["POST","GET"])
def login():
    params = request.json
    result = current_app.config['DB'].login(params.get('username'), params.get("password"))
    if not result:
        return jsonify({"code":400, "message":"用户名或密码有误"})
    else:
        ## 登录信息存储在redis中
        cacheinfo = deepcopy(result)
        cacheinfo.pop('token')
        current_app.config['REDIS'].set(f"{result['token']}", json.dumps(cacheinfo), ex= config.LIFESPAN )
        return jsonify({"code":0, "data":result['token']})
    
@user_bp.route('/logout')
def logout():
    print(request.headers)
    token = request.headers.get('Authorization')
    current_app.config['REDIS'].delete(token)
    return jsonify({'code':0})

@user_bp.route('/session', methods=["POST","GET"])
def session():
    
    ## 检查session
    token = request.headers.get('Authorization')
    value = current_app.config['REDIS'].get(token)
    if value:
        return jsonify({"code":0 , "data":json.loads(value)})

    return jsonify({
        "code": 400,
        "message": "Token is expired"
    })

@user_bp.route('/profile')
def profile():
    ## 获取用户信息
    token = request.headers.get('Authorization')
    value = current_app.config['REDIS'].get(token)
    if value:
        return jsonify({"code":0 , "data":json.loads(value)})
    else:
        return jsonify({'code':500, 'message':'获取用户信息失败'})



@user_bp.route('/profile/update')
def profile_update():

    return 'user.profile/update'

@user_bp.route('/password')
def password():
    return 'user.password'

    
@user_bp.route('/bind/username')
def bind_username():
    return 'user.bind/user_name'


@user_bp.route('/resetPass', methods=['POST'])
def resetPass():
    params = request.json
    # {username: "328327361@qq.com", code: "123342", password: "123123", repass: "123123"}
    # TODO 重置密码
    return jsonify({'code':0})
			

@user_bp.record
def log(app):
    logging.info('register user blueprint')
